/*
Copyright (c) 2007,2007 Elizeu Nogueira da R. Jr.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.
    * Neither the name of the Elizeu Nogueira da R. Jr. nor the names of its 
      contributors may be used to endorse or promote products derived from this 
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


This package is based on HypersonicSQL, originally developed by Thomas Mueller.
and HSQLDB original developed by the HSQL Development Group
*/

package br.com.dreamsource.mobile.jmesql;

import br.com.dreamsource.mobile.jmesql.exceptions.SQLException;
import java.io.*;
import java.util.*;
import br.com.dreamsource.mobile.jmesql.sql.Types;

class Column {
    private static Hashtable hTypes;
    final static int CHAR = Types.CHAR;
    final static int INTEGER = Types.INTEGER;
    final static int FLOAT = Types.FLOAT;
    final static int VARCHAR = Types.VARCHAR;
    final static int DATE = Types.DATE;

    final static int TYPES[] = {
	CHAR, INTEGER, FLOAT,VARCHAR, DATE
    };
    
    String		     sName;
    int			     iType;
    private boolean	     bNullable;
    private boolean	     bIdentity;
    
    static {
	hTypes = new Hashtable();
	addTypes(INTEGER, "INTEGER", "int", "java.lang.Integer");
	addType(INTEGER, "INT");
	addType(FLOAT, "FLOAT");		       // this is a Double
	addTypes(VARCHAR, "VARCHAR", "java.lang.String", null);
	addTypes(CHAR, "CHAR", "CHARACTER", null);
	addTypes(DATE, "DATE", "java.sql.Date", null);
    }

    private static void addTypes(int type, String name, String n2, String n3) {
	addType(type, name);
	addType(type, n2);
	addType(type, n3);
    }

    private static void addType(int type, String name) {
	if (name != null) {
	    hTypes.put(name, new Integer(type));
	}
    }

    Column(String name, boolean nullable, int type, boolean identity) {
	sName = name;
	bNullable = nullable;
	iType = type;
	bIdentity = identity;
    }

    boolean isIdentity() {
	return bIdentity;
    }

    static int getTypeNr(String type) throws SQLException {
	Integer i = (Integer) hTypes.get(type);
	Trace.check(i != null, Trace.WRONG_DATA_TYPE, type);
	return i.intValue();
    }

    static String getType(int type) throws SQLException {
	switch (type) {
            case INTEGER:
                return "INTEGER";
            case VARCHAR:
                return "VARCHAR";
            case CHAR:
                return "CHAR";
            case DATE:
                return "DATE";
            case FLOAT:
                return "FLOAT";
            default:
                throw Trace.error(Trace.WRONG_DATA_TYPE, type);
	}
    }

    boolean isNullable() {
	return bNullable;
    }

    static Object add(Object a, Object b, int type) throws SQLException {
	if (a == null || b == null) {
	    return null;
	}
	switch (type) {
            case INTEGER:
                int ai = ((Integer) a).intValue();
                int bi = ((Integer) b).intValue();
                return new Integer(ai + bi);
            case FLOAT:
                double ad = ((Double) a).doubleValue();
                double bd = ((Double) b).doubleValue();
                return new Double(ad + bd);
            case VARCHAR:

            case CHAR:
                return (String) a + (String) b;
            default:
                throw Trace.error(Trace.FUNCTION_NOT_SUPPORTED, type);
	}
    }

    static Object concat(Object a, Object b) throws SQLException {
	if (a == null) {
	    return b;
	} else if (b == null) {
	    return a;
	}
        return convertObject(a) + convertObject(b);
    }

    static Object negate(Object a, int type) throws SQLException {
	if (a == null) {
	    return null;
	}
	switch (type) {
            case INTEGER:
                return new Integer(-((Integer) a).intValue());
            case FLOAT:
                return new Double(-((Double) a).doubleValue());
            default:
                throw Trace.error(Trace.FUNCTION_NOT_SUPPORTED, type);
	}
    }

    static Object multiply(Object a, Object b, int type) throws SQLException {
	if (a == null || b == null) {
	    return null;
	}
        switch (type) {
            case INTEGER:
                int ai = ((Integer) a).intValue();
                int bi = ((Integer) b).intValue();
                return new Integer(ai * bi);
            case FLOAT:
                double ad = ((Double) a).doubleValue();
                double bd = ((Double) b).doubleValue();
                return new Double(ad * bd);
            default:
                throw Trace.error(Trace.FUNCTION_NOT_SUPPORTED, type);
	}
    }

    static Object divide(Object a, Object b, int type) throws SQLException {
	if (a == null || b == null) {
	    return null;
	}
	switch (type) {
            case INTEGER:
                int ai = ((Integer) a).intValue();
                int bi = ((Integer) b).intValue();
                Trace.check(bi != 0, Trace.DIVISION_BY_ZERO);
                return new Integer(ai / bi);
            case FLOAT:
                double ad = ((Double) a).doubleValue();
                double bd = ((Double) b).doubleValue();
                return bd == 0 ? null : new Double(ad / bd);
            default:
                throw Trace.error(Trace.FUNCTION_NOT_SUPPORTED, type);
	}
    }


    static Object subtract(Object a, Object b, int type) throws SQLException {
	if (a == null || b == null) {
	    return null;
	}
	switch (type) {
            case INTEGER:
                int ai = ((Integer) a).intValue();
                int bi = ((Integer) b).intValue();
                return new Integer(ai - bi);
            case FLOAT:
                double ad = ((Double) a).doubleValue();
                double bd = ((Double) b).doubleValue();
                return new Double(ad - bd);
            default:
                throw Trace.error(Trace.FUNCTION_NOT_SUPPORTED, type);
	}
    }

    static Object sum(Object a, Object b, int type) throws SQLException {
	if (a == null) {
	    return b;
	}
        if (b == null) {
	    return a;
	}
	switch (type) {

            case INTEGER:
                return new Integer(((Integer) a).intValue() + ((Integer) b).intValue());

            case FLOAT:
                return new Double(((Double) a).doubleValue() + ((Double) b).doubleValue());
            default:
                Trace.error(Trace.SUM_OF_NON_NUMERIC);
	}
	return null;
    }

    static Object avg(Object a, int type, int count) throws SQLException {
	if (a == null || count == 0) {
	    return null;
	}
	switch (type) {
            case INTEGER:
                return new Integer(((Integer) a).intValue() / count);
            case FLOAT:
                return new Double(((Double) a).doubleValue() / count);
            default:
                Trace.error(Trace.SUM_OF_NON_NUMERIC);
	}
	return null;
    }

    static Object min(Object a, Object b, int type) throws SQLException {
	if (a == null) {
	    return b;
	}
	if (b == null) {
	    return a;
	}
	if (compare(a, b, type) < 0) {
	    return a;
	}
	return b;
    }

    static Object max(Object a, Object b, int type) throws SQLException {
	if (a == null) {
	    return b;
	}
	if (b == null) {
	    return a;
	}
	if (compare(a, b, type) > 0) {
	    return a;
	}
	return b;
    }


    static int compare(Object a, Object b, int type) throws SQLException {
	int i = 0;
	if (a == null) {
	    if (b == null) {
		return 0;
	    }
	    return -1;
	}
	if (b == null) {
	    return 1;
	}

	switch (type) {
            case INTEGER:
                int ai = ((Integer) a).intValue();
                int bi = ((Integer) b).intValue();
                return (ai > bi) ? 1 : (bi > ai ? -1 : 0);
            case FLOAT:
                double ad = ((Double) a).doubleValue();
                double bd = ((Double) b).doubleValue();
                return (ad > bd) ? 1 : (bd > ad ? -1 : 0);
            case VARCHAR:
                i = ((String) a).compareTo((String) b);
                break;

            case CHAR:
                i = Library.rtrim((String) a).compareTo(Library.rtrim((String) b));
                break;
            case DATE:
//	    if (((java.util.Date) a).after((java.util.Date) b)) {
//		return 1;
//	    } else if (((java.util.Date) a).before((java.util.Date) b)) {
//		return -1;
//	    } else {
		return 0;
//	    }
            default:
                throw Trace.error(Trace.FUNCTION_NOT_SUPPORTED, type);
	}
	return (i > 0) ? 1 : (i < 0 ? -1 : 0);
    }

    static Object convertString(String s, int type) throws SQLException {
	if (s == null) {
	    return null;
	}
	switch (type) {
            case INTEGER:
                return new Integer(Integer.parseInt(s));
            case FLOAT:
                return new Double(Double.parseDouble(s));
            case VARCHAR:
            case CHAR:
                return s;
            case DATE:
                java.util.Date d = new java.util.Date(Long.parseLong(s));
                return d.toString();
            default:
                throw Trace.error(Trace.FUNCTION_NOT_SUPPORTED, type);
	}
    }

    static String convertObject(Object o) {
	if (o == null) {
	    return null;
	}
	return o.toString();
    }

    static Object convertObject(Object o, int type) throws SQLException {
	if (o == null) {
	    return null;
	}
	return convertString(o.toString(), type);
    }

    static String createString(Object o, int type) throws SQLException {
	if (o == null) {
	    return "NULL";
	}
	switch (type) {
            case DATE:
                return "'" + o.toString() + "'";
            case VARCHAR:
            case CHAR:
                return createString((String) o);
            default:
                return o.toString();
	}
    }

    static String createString(String s) {
	StringBuffer b = new StringBuffer().append('\'');
	if (s != null) {
	    for (int i = 0, len = s.length(); i < len; i++) {
		char c = s.charAt(i);
		if (c == '\'') {
		    b.append(c);
		}
		b.append(c);
	    }
	}
	return b.append('\'').toString();
    }

    static Object[] readData(DataInput in, int l) throws IOException, SQLException {
	Object data[] = new Object[l];
	for (int i = 0; i < l; i++) {
	    int    type = in.readInt();
	    Object o = null;
	    switch (type) {
                case INTEGER:
                    o = new Integer(in.readInt());
                    break;
                case FLOAT:
                    o = new Double(Double.longBitsToDouble(in.readLong()));
                    break;
                case VARCHAR:
                case CHAR:
                    o = in.readUTF();
                    break;
                case DATE:
                    o = new java.util.Date(Long.parseLong(in.readUTF()));
                    break;
                default:
                    throw Trace.error(Trace.FUNCTION_NOT_SUPPORTED, type);
	    }
	    data[i] = o;
	}
	return data;
    }

    static void writeData(DataOutput out, Object data[], Table t) throws IOException {
	int len = t.getInternalColumnCount();
	int type[] = new int[len];
	for (int i = 0; i < len; i++) {
	    type[i] = t.getType(i);
	}
	writeData(out, len, type, data);
    }

    static void writeData(DataOutput out, int l, int type[],
			  Object data[]) throws IOException {
	for (int i = 0; i < l; i++) {
	    Object o = data[i];

	    if (o == null) {
		out.writeInt(0);
	    } else {
		int t = type[i];
		out.writeInt(t);
		switch (t) {
                    case INTEGER:
                        out.writeInt(((Integer) o).intValue());
                        break;
                    case FLOAT:
                        out.writeLong(Double.doubleToLongBits(((Double) o).doubleValue()));
                        break;
                    default:
                        out.writeUTF(o.toString());
                        break;
		}
	    }
	}
    }

    static int getSize(Object data[], Table t) {
	int l = data.length;
	int type[] = new int[l];
	for (int i = 0; i < l; i++) {
	    type[i] = t.getType(i);
	}
	return getSize(data, l, type);
    }

    private static int getSize(Object data[], int l, int type[]) {
	int s = 0;
	for (int i = 0; i < l; i++) {
	    Object o = data[i];
	    s += 4;
	    if (o != null) {
		switch (type[i]) {
                    case INTEGER:
                        s += 4;
                        break;
                    case FLOAT:
                        s += 8;
                        break;
                    default:
                        s += getUTFsize(o.toString());
		}
	    }
	}

	return s;
    }

    private static int getUTFsize(String s) {
	if (s == null) {
	    s = "";
	}
	int len = s.length();
	int l = 2;
	for (int i = 0; i < len; i++) {
	    int c = s.charAt(i);
	    if ((c >= 0x0001) && (c <= 0x007F)) {
		l++;
	    } else if (c > 0x07FF) {
		l += 3;
	    } else {
		l += 2;
	    }
	}
	return l;
    }

}
